package manager;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import utils.DBConnector;

/**
 * Servlet implementation class UserSchedule
 */
public class UserSchedule extends BaseCMServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserSchedule() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/xml");
		if (request.getSession(false) == null || request.getSession(false).getAttribute("username") == null){
			response.sendError(HttpServletResponse.SC_FORBIDDEN, "Please login first");
			return;
		}
		
		String username = request.getSession(false).getAttribute("username").toString();
		PreparedStatement stmnt;
		ResultSet res = null;
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
			stmnt = dbConn.getConnection().prepareStatement(
				"SELECT  uc.course_name, session_day, session_start_time, session_end_time " 	+
				"FROM user_courses uc, course_sessions cs " 		+
				"where uc.username = ? " 						+
				"and uc.course_name = cs.course_name; " );

		stmnt.setString(1, username);
		
		res = stmnt.executeQuery();

		DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder;
		
		docBuilder = dbfac.newDocumentBuilder();
		Document doc = docBuilder.newDocument();
    
		Element root = doc.createElement("Schedule");
		doc.appendChild(root);
//		Element scriptElement = doc.createElement("script");
//		scriptElement.setAttribute("src", "applyXSL.js");
//		root.appendChild(scriptElement);
    
		while(res.next()){
			Element courseElement = getOrCreateCourse(res.getString(1), root, doc);
			Element sessionElement = doc.createElement("Session");
			Element dayElement = doc.createElement("Day");
			Text textDay = doc.createTextNode(Integer.toString(res.getInt(2)));
			
			courseElement.appendChild(sessionElement);
			sessionElement.appendChild(dayElement);
			dayElement.appendChild(textDay);
			Element beginElement = doc.createElement("BeginTime");
			Text textBegin = doc.createTextNode(Integer.toString(res.getInt(3)));
			
			sessionElement.appendChild(beginElement);
			beginElement.appendChild(textBegin);
			
			Element endElement = doc.createElement("EndTime");
			Text textEnd = doc.createTextNode(Integer.toString(res.getInt(4)));
			
			sessionElement.appendChild(endElement);
			endElement.appendChild(textEnd);
		
		}
		
		PrintWriter out = response.getWriter();
		
		TransformerFactory transfac = TransformerFactory.newInstance();
		transfac.setAttribute("indent-number", new Integer(2));
		Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        

        //create string from xml tree

        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(doc);
        trans.transform(source, result);
        String xmlString = sw.toString();


        //print xml
        out.println(xmlString);

		
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
			
         
	}
		
		
	
	
	Element getOrCreateCourse(String course, Element root, Document doc){
		NodeList courseList = root.getElementsByTagName("Course");
		Element tmpNameElement;
		for(int i = 0; i<courseList.getLength(); i++){
			tmpNameElement = (Element) courseList.item(i).getFirstChild(); 
			String tmpName = tmpNameElement.getTextContent();
			if (tmpName.equals(course)){
				return (Element) tmpNameElement.getParentNode();
			}
			
		}
		Element courseElement = doc.createElement("Course");
		Element nameElement = doc.createElement("Name");
		Text textName = doc.createTextNode(course);
		root.appendChild(courseElement);
		courseElement.appendChild(nameElement);
		nameElement.appendChild(textName);
		return courseElement;

	}
	

}
